package com.example.dqdq.lzyim_asm_tvapp;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.dqdq.lzyim_asm_tvapp.api.API;
import com.example.dqdq.lzyim_asm_tvapp.https.HttpManger;
import com.example.dqdq.lzyim_asm_tvapp.utils.ActivityCollector;
import com.example.dqdq.lzyim_asm_tvapp.utils.FileDownLoad;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Timer;
import java.util.TimerTask;

import static android.support.v7.app.AlertDialog.*;

public class BootAdActivity extends BaseActivity {
    private Timer timer;
    private int recLen = 4;
    private String FileName = "tvAppLoadImg.jpg";
    private String imgPath="";
    private ImageView img;
    private Builder builder;
    private boolean update=false;
    private Bitmap getImageFromAssetsFile(String fileName) {

        Bitmap image = null;
        AssetManager am = getResources().getAssets();

        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return image;

    }

    /**
     * 下载图片
     * @param url
     * @param path
     */
    private void downloadFile(final String url, String path) {
        RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path);
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }

            @Override
            public void onStarted() {
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

            }

            @Override
            public void onSuccess(File result) {

                Log.e("test","path"+result.getPath());
//                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                Log.e("test erro",ex.toString());
//                Toast.makeText(BootAdActivity.this, "下载失败，请检查网络和SD卡", Toast.LENGTH_SHORT).show();
//                finish();

            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
//                finish();

            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);

        setContentView(R.layout.activity_boot_ad);
        String path = "file";
         String SDCard = Environment.getExternalStorageDirectory() + "";
        imgPath = SDCard + "/" + path + "/" + FileName;//文件存储路径
        displayImg();

        initView();
        checkUpdate(BootAdActivity.this);
    }

    /**
     * 显示图片
     */
    private void displayImg()
    {
        File file=new File(imgPath);
        if (!file.exists())
        {
            img= (ImageView) findViewById(R.id.img);
            img.setImageBitmap(getImageFromAssetsFile(FileName));
         }
        else
        {
            img= (ImageView) findViewById(R.id.img);
            Bitmap  bmp = BitmapFactory.decodeFile(imgPath);
//            Bitmap bitmap = getLoacalBitmap(imgPath); //从本地取图片(在cdcard中获取)  //
            img .setImageBitmap(bmp); //设置Bitmap

        }

    }

    /**
     * 加载本地图片
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    private void initView()
    {
        timer = new Timer();
        timer.schedule(task, 1000, 1000);       // timeTask
        String path = "file";
        OutputStream output = null;
        String SDCard = Environment.getExternalStorageDirectory() + "";
        imgPath = SDCard + "/" + path + "/" + FileName;//文件存储路径
        File file = new File(SDCard + "/" + path);
        if (!file.exists()) {
            file.mkdir();//创建存储路径
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                  downloadFile(API.LOAD_IMG_URL,imgPath);
            }
        }).start();
    }
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            update=true;
            String path= (String) msg.obj;
            builder = new Builder(BootAdActivity.this);
            builder.setMessage("检测到更新是否安装升级?");
            builder.setTitle("提示");
            final String finalPath = path;
            builder.setPositiveButton("安装", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setDataAndType(Uri.parse("file://" + finalPath), "application/vnd.android.package-archive");
                    startActivity(i);
                    finish();

                }
            });
            builder.setNegativeButton("取消", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();

                }
            });
            builder.setCancelable(false);

            builder.create().show();

        }
    };

    @Override
    protected void onStop() {
//        finish();
        super.onStop();
    }

    private void checkUpdate(final Context context) {
        x.http().post(HttpManger.getParams(API.APK_UPDATE_URL, "", ""), new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    PackageManager manager = context.getPackageManager();
                    PackageInfo info = null;
                    Log.e("test", result);
                    info = manager.getPackageInfo(context.getPackageName(), 0);
                    int version = info.versionCode;
                    JSONObject object = new JSONObject(result);
                    final JSONObject data=object.getJSONObject("data");
                    Log.e("version",String.valueOf(data.getInt("versioncode")));
                    if (version < data.getInt("versioncode")) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {

                                    update=true;
                                    FileDownLoad fileDownLoad=new FileDownLoad();
                                    String path= null;
                                    path = fileDownLoad.downLoadApk(API.SERVERC_URL+data.getString("download"),context);
                                     Message msg=new Message();
                                    msg.obj=path;

                                      handler.sendMessage(msg);


//                                    initView();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        }).start();
                    }
                    else
                    {
                        initView();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }



    /**
     * 定时显示广告图
     */
    TimerTask task = new TimerTask(){
        @Override
        public void run() {
            runOnUiThread(new Runnable() {      // UI thread
                @Override
                public void run() {

                    if (recLen == 0) {


                        if (!update)
                        finish();
                    }
                    recLen--;
                }
            });
        }
    };
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}
